<template>
  <el-card>
    <div slot="header">
      <h3>潜在商品新增开发需求</h3>
    </div>
    <div>
      <BasicForm
        ref="formData"
        defaultExpandStatus
        formItemWidth="130px"
        :showBtnBar="false"
        :formColumns="formItems"
        :dataSource="formData"
      />
      <skus-table
        ref="skusTable"
        :tableHeight="480"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :actionRender="renderTableBtnAction"
      >
        <!-- 按钮操作栏 -->
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </div>
    <ViewProductDetailsDialog
      :visible.sync="viewProductDetails.visible"
      :search-method="searchProductDetails"
    />
  </el-card>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import ViewProductDetailsDialog from '../components/ViewProductDetailsDialog';
import { FORM_ITEMS, TABLE_COLUMNS } from './constants/latentAdd';
import { LATENT_DEV_POOL_INFO_KEY } from '@/pages/commodity/temporaryManage/latentProductDataAnalysis/constants';
import { getSkuCountCol } from '../developPlan/constants/actionPage';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { isResponseSuccess } from '@/utils/bizUtils';
import {
  commitService,
  getDropDownListService,
  getListFromPotentialAnalysisService,
  getVoListByUniqueKeysService
} from '@/api/commodity/developmentRequirementPlan/developRequirementPool';
export default {
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    ViewProductDetailsDialog
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      btnLoading: {
        submit: false
      },
      viewProductDetails: {
        visible: false,
        curIndex: null
      }
    }
  },
  created () {
    this.updateTableColumns()
    this.setIndustrySelectOptions()
    this.updateInfoData()
  },
  beforeRouteLeave (to, from, next) {
    if (to.name != this.$route.name) {
      localStorage.removeItem(LATENT_DEV_POOL_INFO_KEY)
    }
    next()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const submitBtn = {
        label: '提交',
        method: this.handleSubmit,
        disabled: this.TableInfo.isNullList(),
        loading: this.btnLoading.submit
      }
      // 按钮通用属性填充
      const btnBars = [submitBtn]
      return getListPageBtnsBar(h, btnBars, null)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row, index }) {
      const actionList = [{ label: '删除', method: () => { this.handleDelete(index) } }]
      return getTableAction({ h, row, actionList })
    },
    // 删除
    handleDelete (index) {
      this.TableInfo.removeList(index)
    },
    // 提交
    async handleSubmit () {
      const data = {
        detailList: this.TableInfo.list.map(item => ({
          ...item, skuParamList: item?.skuFrontVoList ?? []
        })),
        ...this.formData,
        ...this.getIndustryInfoBySubmit()
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.$router.push({ name: 'developRequirementPoolList' })
      }
    },
    // 获取行业表单方法
    useIndustryForm () {
      // 获取行业表单item下标
      const getIndex = () => FORM_ITEMS.findIndex(item => item.prop == 'industryNo')
      // 获取初始后的行业下拉options
      const getOptions = list => (list ?? []).map(item => ({
        value: item.industryNo,
        label: item.industryPath
      }))
      return { getIndex, getOptions }
    },
    // 初始化设置行业下拉options
    async setIndustrySelectOptions () {
      const data = { industryName: '' }
      const res = await getDropDownListService(data)
      if (!res?.retData) return
      const { getIndex, getOptions } = this.useIndustryForm()
      if (getIndex() == -1) return
      this.formItems[getIndex()].options = getOptions(res.retData)
    },
    // 获取提交的行业信息
    getIndustryInfoBySubmit () {
      const { getIndex } = this.useIndustryForm()
      const industryOptions = this.formItems[getIndex()]?.options ?? []
      const info = industryOptions.find(item => item.value == this.formData.industryNo)
      if (info) return _.pick(info, ['industryNo', 'industryPath'])
      // 搜寻不到，新增行业信息
      return { industryNo: '', industryPath: this.formData.industryNo }
    },
    // 更新数据集合
    async updateInfoData () {
      const uniqueKeys= JSON.parse(localStorage.getItem(LATENT_DEV_POOL_INFO_KEY) ?? '[]')
      this.formData.devType = this.$route?.query.devType
      const data = { uniqueKeys }
      const res = await getListFromPotentialAnalysisService(data, this.TableInfo.setLoading)
      this.TableInfo.setList(res?.retData ?? [])
    },
    // 更新表列
    updateTableColumns () {
      this.TableInfo.setColumns([
        ...TABLE_COLUMNS,
        getSkuCountCol(this.handleViewProductDetails)
      ])
    },
    // 查看商品明细
    handleViewProductDetails (row, index) {
      this.viewProductDetails.visible = true
      this.viewProductDetails.curIndex = index
    },
    // 查询商品明细
    async searchProductDetails (loadingFn) {
      const skuFrontVoList = this.TableInfo.list[this.viewProductDetails.curIndex]?.skuFrontVoList ?? []
      const data = skuFrontVoList.map(item => item.areaOrderKey)
      const res = await getVoListByUniqueKeysService(data, loadingFn)
      return res
    }
  }
}
</script>
